package org.simplemvc.xml;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlReader {

	private Log logger = LogFactory.getLog(this.getClass());
	
	public Map<String,ActionBean> getFormMapping(String xmlpath) {
		Map<String,ActionBean> mapAction= new HashMap<String,ActionBean>();
		SAXReader reader = new SAXReader();
		Document document = null;
		
		try {
			document = reader.read(new File(xmlpath));
			Element root = document.getRootElement();
			
			for (Iterator<Element> iterator = root.elements("action").iterator(); iterator.hasNext();) {
				ActionBean bean = new ActionBean();
				Element action = iterator.next();
				
				String name = action.attributeValue("name");
				String className = action.attributeValue("class");
				String method = action.attributeValue("method");
				
				bean.setActionName( name );
				bean.setClassName(className);
				bean.setExecuteMethod(method);
				
				List<Element> results = action.elements();
				for(Element result : results ){
					String success = result.attributeValue("name");
					String path = result.getText();
					if ("success".equals(success)){
						bean.setSuccessForward(path);
					} else {
						bean.setFalseForward(path);
					}
				}
				
				mapAction.put(name, bean);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return mapAction;
	}
	
	private void parseAction(){
		
	}
}
